import time
import os
import ansible_runner
import re
from .celery import  app

@app.task
def run_playbook_with_cert(playbook_path, inventory_path):
    back_result = []
    # 配置Runner环境变量
    extravars = {
        'ansible_fact_caching_enabled': False,
        'ansible_user': 'root',
        'ansible_password': 'Emotibot@1',
        'ansible_ssh_port': 22,
        #     'ANSIBLE_VAULT_PASSWORD_FILE': '/root/test/.vault_pass',
        'ANSIBLE_HOST_KEY_CHECKING': 'False'
    }

    # 执行Playbook
    runner = ansible_runner.run(
        playbook=playbook_path,
        inventory=inventory_path,
        extravars=extravars,
        quiet=True,  # 显示详细输出
        json_mode=True  # 返回JSON格式结果
    )

    # 处理执行结果
    try:
        if runner.status == 'failed':
            print("Ansible Playbook执行成功")
            for event in runner.events:
                if event['event'] == 'runner_on_ok':
                    for k, v in event.items():
                        if k == "event_data":
                            result = (v["task"], v["remote_addr"], "successful")
                            back_result.append(result)
                            print("\033[32m" + str(result) + "\033[0m")
                else:
                    for k, v in event.items():
                        if k == "stdout":
                            if re.search("fatal", v):
                                ss = (v.split("=>")[0].split(":")[1])
                                to_remove = "[]"
                                result = re.sub(f"[{re.escape(to_remove)}]", "", ss)
                                resultbak = result, v.split("=>")[1].split(",")[1], "failed"
                                back_result.append(resultbak)
                                print("\033[31m" + str(resultbak) + "\033[0m")
        #  print(f"执行失败，返回码: {runner.rc}")
        #  print("错误输出:", runner.msg)
    except Exception as e:
        print("错误输出:", runner.stderr)
    return back_result